#include "common.hpp"

int main()
{
    key_t k = ftok(PATH_NAME, PROJ_ID);
    assert(k != -1);
    cout << "create key done client key : " << k << endl;

    //获取共享内存
    int shmid = shmget(k, SHM_SIZE, IPC_CREAT);
    assert(shmid >= 0);
    cout << "create shm success client key : " << k << endl;
    // sleep(10);

    //关联共享内存
    char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    assert(shmaddr != nullptr);
    cout << "attach shm success client key : " << k << endl;
    // sleep(10);

    //使用
    //client将共享内存看做一个char类型的buffer
    int fd = OpenFIFO(FIFO_PATH, WRITE);

    while (true)
    {
        ssize_t s = read(0, shmaddr, SHM_SIZE - 1);
        if (s > 0)
        {
            shmaddr[s - 1] = 0;
            Signal(fd);
            if (strcmp(shmaddr, "quit") == 0) break;
        }
    }

    CloseFifo(fd);

    // char a = 'a';
    // for (; a <= 'z'; a++)
    // {
    //     shmaddr[a - 'a'] = a;
    //     //每次都向共享内存的起始地址写入
    //     snprintf(shmaddr, SHM_SIZE - 1, "hello server, 我是其他进程， 我的pid : %d, message : %c\n", getpid(), a);
    //     sleep(1);
    // }
    // strcpy(shmaddr, "quit");

    //取消关联共享内存
    int n = shmdt(shmaddr);
    assert(n != -1);
    cout << "detach shm success client key : " << k << endl;
    // sleep(10);

    //Client不需要删除共享内存

    return 0;
}